package org.bdware.doip.endpoint.doipClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.concurrent.Future;
import org.bdware.doip.core.codec.packet.PacketNettyUDPCodec;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;

public class NettyDoipUDPClientChannel extends NettyDoipClientChannel {

    int clientPort;
    EventLoopGroup group;
    final Bootstrap b = new Bootstrap();
    public NettyDoipUDPClientChannel() throws URISyntaxException {
        this(0);
    }

    public NettyDoipUDPClientChannel(int cp) throws URISyntaxException {
        clientPort = cp;
    }

    @Override
    public void close() {
        remoteAddress = null;
        isConnected = false;
        if(handler != null) handler.close();
        if(group != null) {
            Future<?> future = group.shutdownGracefully();
            future.syncUninterruptibly();
        }
    }

    @Override
    public void connect(String targetUrl) throws URISyntaxException {
        URI uri = new URI(targetUrl);
//        logger.debug("[URI Parse]scheme:" + uri.getScheme() + "  host: " + uri.getHost() + "  port: " + uri.getPort());
        if(group==null){
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
            group = new NioEventLoopGroup(10);
            b.group(group);
            super.handler = new NettyDoipClientHandler();
            b.channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(
                            new ChannelInitializer<DatagramChannel>() {
                                @Override
                                protected void initChannel(DatagramChannel ch) {
                                    ch.pipeline()
                                            .addLast(new PacketNettyUDPCodec())
                                            .addLast(handler);
                                }
                            });
        }
        remoteAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
        try {
            super.channel = b.bind(clientPort).sync().channel();
            handler.setChannel(channel);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        isConnected = true;
    }
}
